package org.example.algorithm.binarytree;

import org.example.algorithm.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 先序遍历二叉树（递归+非递归）
 */
public class PreorderTraversalSolution {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(3);
        treeNode.left = new TreeNode(5);
        treeNode.right = new TreeNode(7);
        treeNode.left.left = new TreeNode(9);
        treeNode.left.right = new TreeNode(8);
        treeNode.left.left.left = new TreeNode(2);
        List<Integer> result = preorderTraversal(treeNode);
        System.out.println(result);
    }

    public static List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Stack<TreeNode> nodeStack = new Stack<>();
        nodeStack.push(root);
        while (!nodeStack.isEmpty()) {
            TreeNode cur = nodeStack.pop();
            result.add(cur.val);
            if (cur.right != null) {
                nodeStack.push(cur.right);
            }
            if (cur.left != null) {
                nodeStack.push(cur.left);
            }
        }
        return result;
    }

    public static List<Integer> preorderTraversal2(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        doPreorderTraversal(root, result);
        return result;
    }

    public static void doPreorderTraversal(TreeNode treeNode, List<Integer> result) {
        if (treeNode == null) {
            return;
        }
        result.add(treeNode.val);
        doPreorderTraversal(treeNode.left, result);
        doPreorderTraversal(treeNode.right, result);
    }
}
